import { nanoid10 } from '@/utils';
import { Popup, TreeList } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import * as ReactDOMClient from 'react-dom/client';
import { useModel } from 'umi';
//@ts-ignore
import DevPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup';
//@ts-ignore
import DevToolBar from '~/public/cpas-ui/components-ui/express-components/DevToolBar';
import { getSqlApiList } from '../SummaryAnalysis/server';
const WordEdit = forwardRef((props: any, ref: any) => {
  const [nanoid16, Setnanoid16] = useState('buildkey');
  const { initialState } = useModel('@@initialState');
  const { dbname } = initialState?.curPart;
  const [isViewZY, setIsviewZY] = useState(false);
  const DwordlistPopRef = useRef<any>();
  const [wordlistPop, setwordlistPop] = useState<any[]>([]);
  const [CurrentRow, setCurrentRow] = useState<{
    DWord: string;
    rowIndex?: Number;
    id?: number;
    rowid?: number;
  }>();
  const CurrentRowDword = useRef<any>();

  const comfirRef = useRef<any>();

  const [isEditMode, setIsEditMode] = useState(false);
  const WordtoolbarItems = [
    // {
    //   html: '<div style="font-weight:normal">疑点字词：</div>',
    //   location: 'before',
    //   options: {
    //     width: 150,
    //   },
    // },
    {
      widget: 'dxTextBox',
      name: 'ew',
      options: {
        readOnly: !isEditMode,
        width: 150,
        value: CurrentRow?.DWord,
        showClearButton: true,
        onInput: ({ component, event }: any) => {
          console.log(event.target.value);
          CurrentRowDword.current = { DWord: event.target.value };
          // <{ DWord: string; rowIndex?: Number; id?: number }>
          // setCurrentRow({ ...CurrentRow, DWord: event.target.value });
        },
      },
      location: 'before',
    },
    {
      widget: 'dxButton',
      visible: !isEditMode,
      options: {
        text: '增加',
        onClick: function (e: any) {
          //   debugger;
          setIsEditMode(!isEditMode);
          setCurrentRow({
            ...CurrentRow,
            DWord: '',
          });
          addWordSave.current = 1;
        },
      },
    },
    {
      widget: 'dxButton',
      visible: !isEditMode,
      options: {
        text: '修改',
        onClick: function (e: any) {
          if (CurrentRow?.id) {
            addWordSave.current = false;
            setIsEditMode(!isEditMode);
          } else {
            notify('请选中疑点字词', 'error', 1000);
          }
        },
      },
    },
    {
      widget: 'dxButton',
      visible: !isEditMode,
      options: {
        text: '删除',
        onClick: async () => {
          debugger;
          comfirRef.current.show({
            title: '提示',
            okCallback: async () => {
              if (CurrentRow?.id) {
                await deleteDWord(CurrentRow?.id as number);
              } else {
                notify('请选中疑点字词', 'error', 1000);
              }

              // eventsSaveData.current.push({rowState: 'delete', guid: key})
            },
          });

          // DwordlistPopRef.current._instance.deleteRow(CurrentRow?.rowIndex);
          // debugger;
          // await DwordlistPopRef.current._instance.saveEditData();
        },
      },
    },
    {
      widget: 'dxButton',
      visible: isEditMode,
      options: {
        text: '确定',
        onClick: async function (e: any) {
          // await DwordlistPopRef.current._instance.saveEditData();

          // 修改或者是新增吗
          if (CurrentRowDword.current?.DWord?.trim() === '') {
            if (addWordSave.current) {
              notify('请输入字词', 'error', 2000);
              return;
            } else {
              setIsEditMode(!isEditMode);
            }
          }
          if (CurrentRowDword.current?.DWord) {
            if (addWordSave.current) {
              if (
                wordlistPop?.filter((a: any) => a.DWord === CurrentRowDword.current.DWord).length
              ) {
                return notify('输入的字词已经存在了', 'error', 2000);
              }
              await insertDWord(CurrentRowDword.current.DWord);
              let words = await geth_DoubtfulWord();
              let word = words?.filter((a: any) => a.DWord === CurrentRowDword.current.DWord);
              // CurrentRow.current = { DWord: addWordSave.current };

              if (word.length) {
                setCurrentRow(word[0]);
              }
              return;
            } else {
              if (CurrentRowDword.current.DWord === CurrentRow?.DWord) {
                setIsEditMode(!isEditMode);
                return;
              }
              if (
                wordlistPop?.filter((a: any) => a.DWord === CurrentRowDword.current.DWord).length
              ) {
                return notify('输入的字词已经存在了', 'error', 2000);
              }
              return await updateDWord(CurrentRowDword.current.DWord, CurrentRow?.id as number);
            }
          } else {
            if (!addWordSave.current) {
              setIsEditMode(!isEditMode);
            }
          }
        },
      },
    },
    {
      widget: 'dxButton',
      visible: isEditMode,
      options: {
        text: '取消',
        onClick: function (e: any) {
          //   debugger;

          setIsEditMode(!isEditMode);
          if (addWordSave.current) {
            addWordSave.current = false;
            debugger;
            let word = wordlistPop?.filter((a: any) => a.id === CurrentRow?.id);
            if (word.length) {
              setCurrentRow({
                ...CurrentRow,
                DWord: word[0].DWord,
              });
            }
            // CurrentRow.current = { DWord: addWordSave.current };
          }
        },
      },
    },
  ];
  const addWordSave = useRef<any>(false);

  useEffect(() => {
    console.log('ewe');
    debugger;
    Setnanoid16(nanoid10());
  }, [isViewZY]);
  const onSelectionChangedWord = (e: any) => {
    const { selectedRowKeys, selectedRowsData } = e;
    debugger;
    if (selectedRowsData?.length) {
      setCurrentRow({
        DWord: selectedRowsData[0].DWord,
        rowIndex: 1,
        id: selectedRowsData[0].id,
        rowid: selectedRowsData[0].rowid,
      });
    } else {
      debugger;
    }
  };

  const geth_DoubtfulWord = async () => {
    let d = await getSqlApiList('get.h_DoubtfulWord', {
      dbname: dbname,
    });
    if (d.data?.length) {
      setwordlistPop(arr_index(d.data));
      console.log(arr_index(d.data));
      return arr_index(d.data);
    } else {
      return [];
    }
  };

  const insertDWord = async (DWord: string) => {
    const dd: any = await getSqlApiList('insert.h_DoubtfulWord', { dbname: dbname, DWord: DWord });
    if (dd.ok) {
      setIsEditMode(!isEditMode);
      CurrentRowDword.current = '';
      notify('添加成功', 'success', 2000);
    } else {
      notify('添加失败', 'error', 2000);
    }
  };

  const updateDWord = async (DWord: string, id: number) => {
    const dd: any = await getSqlApiList('update.h_DoubtfulWord', {
      dbname: dbname,
      DWord: DWord,
      id: id,
    });
    if (dd.ok) {
      setwordlistPop(
        wordlistPop?.map((a: any) => {
          if (a.id === id) {
            return { ...a, DWord: DWord };
          } else {
            return a;
          }
        }),
      );
      setCurrentRow({
        ...CurrentRow,
        DWord: DWord,
      });
      setIsEditMode(!isEditMode);
      CurrentRowDword.current = '';
      notify('修改成功', 'success', 2000);
    } else {
      notify('修改失败', 'error', 2000);
    }
  };
  useImperativeHandle(ref, () => {
    return {
      showPop: async ({ words }: any) => {
        if (words?.length) {
          setCurrentRow({
            DWord: words?.length ? words[0].DWord : '',
            // rowIndex: 1,
            id: words[0].id,
            rowid: 0,
          });
        }
        setIsEditMode(false);
        setwordlistPop(words);
        setIsviewZY(true);
        // Setnanoid16(nanoid10());
        // debugger;
      },
    };
  });

  const arr_index = (a: any[]) => {
    return a.map((b: any, c: number) => {
      return { ...b, rowid: c };
    });
  };
  const deleteDWord = async (id: number) => {
    const dd: any = await getSqlApiList('delete.h_DoubtfulWord', {
      dbname: dbname,
      id: id,
    });
    if (dd.ok) {
      let data = arr_index(wordlistPop?.filter((a: any) => a.id !== CurrentRow?.id));
      if (data.length) {
        debugger;
        if (data.length === CurrentRow?.rowid) {
          // 最后一个，rowid-1
          let current = data.filter(
            (a: any) => a.rowid === (CurrentRow?.rowid && CurrentRow.rowid - 1),
          );
          setCurrentRow(current[0]);
        } else {
          let current = data.filter((a: any) => a.rowid === CurrentRow?.rowid);
          // 第一个 rowid 不变
          setCurrentRow({ ...CurrentRow, DWord: current[0]?.DWord, id: current[0]?.id });
        }
      } else {
        setCurrentRow({ DWord: '', rowid: 0, id: 1 });
      }
      setwordlistPop(data);

      notify('删除成功', 'success', 2000);
    } else {
      notify('删除失败', 'error', 2000);
    }
  };

  const table = () => {
    return (
      <div style={{ width: '100', height: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <span style={{ whiteSpace: 'nowrap' }}>疑点字词：</span>
          <DevToolBar.Default items={WordtoolbarItems} style={{ padding: '8px 0' }} />
        </div>

        <DevPopup.Default ref={comfirRef} width={80} height={200}>
          {() => {
            return <span>是否要删除此记录？</span>;
          }}
        </DevPopup.Default>
        <span>共有关键字记录： {wordlistPop?.length ?? 0}</span>
        <TreeList
          ref={DwordlistPopRef}
          height={'44vh'}
          dataSource={wordlistPop}
          // onCellClick={onClickWord}
          key={nanoid16}
          keyExpr="rowid"
          rootValue={-1}
          selection={{
            mode: 'single',
          }}
          // defaultSelectedRowKeys={[CurrentRow?.rowid]}
          onSelectionChanged={onSelectionChangedWord}
          selectedRowKeys={[CurrentRow?.rowid]}
          // focusedRowEnabled={true}
          // defaultFocusedRowIndex={CurrentRow?.rowid}
          // hoverStateEnabled={true}
          showBorders={true}
          loadPanel={{ enabled: false }}
          scrolling={{
            mode: 'standard',
            // rowRenderingMode: 'virtual',
            // renderAsync: true,
          }}
          paging={{
            // enabled: true,
            pageSize: 0,
          }}
          editing={{
            mode: 'row',
            // allowDeleting: true,
            // confirmDelete: true,
          }}
          showRowLines={true}
          columns={[
            {
              alignment: 'left',
              // minWidth: 40,
              width: 50,
              cellTemplate: (rowhtml: any, row: any) => {
                const { rowIndex, data } = row;
                // console.log('li row', rowIndex);
                // debugger;
                return ReactDOMClient.createRoot(rowhtml).render(
                  <div style={{ margin: 0 }}>{data.rowid + 1}</div>,
                );
              },
            },
            {
              caption: '疑点字词',
              dataField: 'DWord',
              alignment: 'left',
              fixedPosition: 'left',
              dataType: 'string',
            },
          ]}
        ></TreeList>
      </div>
    );
  };
  return (
    <Popup
      key={nanoid16}
      resizeEnabled={true}
      height={'65vh'}
      width={'45vw'}
      title={'疑点字词维护'}
      visible={isViewZY}
      onHiding={() => {
        props.reFreash();
        setIsviewZY(false);
      }}
      contentRender={table}
    ></Popup>
  );
});
export default WordEdit;
